package com.itcc.controller;

import com.itcc.service.FileDownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/fileService")
public class DownLoadController {

    @Autowired
    private FileDownloadService fileDownloadService;

    @PostMapping("/download")
    public Result downloadFile(@RequestBody Map<String, String> payload) {

        String fileUrl = "";
        String url = payload.get("url");

        try {
            // 调用下载服务
            fileUrl = fileDownloadService.downloadFile(url);
            // 返回下载链接
//            return ResponseEntity.ok().body(fileUrl);
            return new Result(Code.DOWNLOAD_SUCCESS, fileUrl);
        } catch (Exception e) {
            return new Result("下载失败：" + e.getMessage());
//            return ResponseEntity.ok().body("下载失败：" + e.getMessage());
        }

    }

    @GetMapping("/down.do")
    public ModelAndView downloadFile(HttpSession session) {

        ModelAndView download = new ModelAndView();
        if(session.getAttribute("user") == null){
            download.setViewName("redirect:/");
            return download;
        }

        download.setViewName("down");
        return download;
    }

}
